#!/root/miniconda3/bin/python
import os
import sys
import requests
import json
import time

def post(argv):
    PJ_NAME = os.getenv('PJ_NAME') or "PJ_NAME_CONFIG_ERROR"
    BUILD_NUMBER = os.getenv('BUILD_NUMBER') or "123"
    GIT_COMMIT = os.getenv('GIT_COMMIT') or "123456"
    GIT_BRANCH = (os.getenv('GIT_BRANCH') or "gitee/test").split('/')[1]
    POST_URL = os.getenv('POST_URL') or "https://open.feishu.cn/open-apis/bot/v2/hook/14719364-818d-4f88-9057-7c9f0eaaf6ae"

    if len(argv) >= 2:
        if argv[1] == 'github':
            if GIT_BRANCH.endswith('master'):
                print('git@github.com:fastNLP/{}.git'.format(PJ_NAME))
                os.system('git remote add github git@github.com:fastNLP/{}.git'.format(PJ_NAME))
                os.system('git push github HEAD:master')
            if GIT_BRANCH.endswith('dev'):
                print('git@github.com:fastNLP/{}.git'.format(PJ_NAME))
                os.system('git remote add github git@github.com:fastNLP/{}.git'.format(PJ_NAME))
                os.system('git push github HEAD:dev')
            return
        if argv[1] == "1":
            tag = 1
        else:
            tag = 0
    else:
        tag = 0
    file_path =  f"""/ci/{PJ_NAME}/report-{BUILD_NUMBER}-{GIT_BRANCH}-{GIT_COMMIT}.html"""
    print(file_path)
    print(os.path.exists('test_results.html'))
    os.system('mkdir -p /ci/{}'.format(PJ_NAME))
    os.system('cp test_results.html {}'.format(file_path))
    data = {
        "msg_type": "post",
        "content": {
            "post": {
                "zh_cn": {
                    "title": "Jenkins 构建通知 [{}]".format(PJ_NAME),
                    "content": [
                        [
                            {
                                "tag": "text",
                                "text": "项目的第{}次构建{}，请查看".format(BUILD_NUMBER,"已完成" if tag == 0 else "失败")
                            },{
                                "tag": "a",
                                "text": "测试结果",
                                "href": "http://ci.fastnlp.top/_ci/{}".format(file_path[4:])
                            },{
                                "tag": "text",
                                "text": "\n点击查看 Jenkins "
                            },{
                                "tag": "a",
                                "text": "详情页",
                                "href": "http://test.fastnlp.top/blue/organizations/jenkins/{}/detail/{}/{}/pipeline".format(PJ_NAME, PJ_NAME, BUILD_NUMBER)
                            }
                        ]
                    ]
                }
            }
        }
    }

    requests.post(url=POST_URL, headers={'Content-Type': 'application/json'}, data=json.dumps(data))


if __name__ == "__main__":
    post(sys.argv)